﻿// DateConverter.cs
//

using System;
using System.Globalization;
using System.Security.Principal;
using System.Windows;
using System.Windows.Data;

namespace BookClub.Core {

    public sealed class UserConverter : IValueConverter {

        public bool RequiresAuthentication {
            get;
            set;
        }

        public string RequiredRole {
            get;
            set;
        }

        #region Implementation of IValueConverter
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            bool allowed = true;

            IPrincipal user = value as IPrincipal;
            if (user == null) {
                allowed = false;
            }
            else {
                if (RequiresAuthentication && (user.Identity.IsAuthenticated == false)) {
                    allowed = false;
                }
                if ((String.IsNullOrEmpty(RequiredRole) == false) &&
                    (user.IsInRole(RequiredRole) == false)) {
                    allowed = false;
                }
            }

            return allowed ? Visibility.Visible : Visibility.Collapsed;
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            DateTime dt = (DateTime)value;
            return dt.ToUniversalTime();
        }
        #endregion
    }
}
